<?php


namespace app\award;

// 处理复购分红
use app\models\order\Order;
use app\models\SetUserUp;
use app\models\user\User;
use app\models\user\UserLevel;
use app\models\ZSetting;
use app\services\Chain;
use yii\helpers\ArrayHelper;

class Profit
{
    protected static $users = [];

    public static function getList()
    {
        // 指定等级的才有分红
        $users = User::find()
            // ->where(['>', 'c1', 0])
            // ->orWhere(['>', 'c2', 0])
            ->where(['>=', 'level', UserLevel::$keys['svip2']])
            ->select(['id'])
            ->column();

        // var_dump($users);exit;

        // 子团队,
        $data = [];
        foreach ($users as $user) {
            $children = Chain::getChildrenAllOperate($user, false, ['id']);
            $children = ArrayHelper::getColumn($children, 'id');

            $manager = Chain::getChildrenAllOperate($user, true, ['id']);
            $manager = ArrayHelper::getColumn($manager, 'id');

            $data[] = [
                'id' => $user,
                'children' => $children,
                'manager' => $manager,
            ];
        }

        // 清除没有子合伙人的
        // 这里相当于, 没有manager的人要去除
        // 主要给下面去重使用
        $x = ArrayHelper::getColumn($data, 'manager');
        foreach ($x as $k => $v) {
            if (!$v) {
                unset($x[$k]);
            }
        }

        // 去子合伙人
        // 存在于别人的团队中, 就是子合伙人
        // id 存在于 别的 manager中, 肯定是子合伙人
        foreach ($users as $key => $user) {
            foreach ($x as $item) {
                if (in_array($user, $item)) {
                    unset($users[$key]);
                }
            }
        }

        // 此时已经找出最顶层的合伙人了
        // var_dump($users);exit;

        // var_dump($data);exit;
        // 此数据后面还要用, 保存到类中
        self::$users = $data;

        $needs = self::getData($users);
        $list = self::getOrder($needs);

        // var_dump($list);exit;
        foreach ($list as &$item) {
            if ($item['amount'] == 0) {
                continue;
            }

            // 极差, 减去第1层全部子团队佣金
            $first_child = self::firstChild($item, $list);

            $item['first_child'] = $first_child;
            $item['real_amount'] = $item['amount'] - $first_child;
        }

        return $list;
    }

    private static function firstChild($child, $users)
    {

        $sum = 0;

        foreach ($child['manager'] as $id) {

            // 关系链上, 第1个运营中心
            // $first = Chain::getFirstOperator($id);
            $first = Chain::getReferrerChainOneId($id, [
                // UserLevel::$keys['svip1'],
                UserLevel::$keys['svip2'],
                UserLevel::$keys['svip3']
            ]);

            // 如果第1个推荐人, 刚好是$child,
            // 则说明 此子合伙人是 $child的第1层 子团队
            if ($first && $first['id'] == $child['id']) {
                if (isset($users[$id]) && isset($users[$id]['amount'])) {
                    $sum += $users[$id]['amount'];
                }
            }
        }

        return $sum;
    }

    // 为了少查数据库, 获取相应数据
    private static function getData($users)
    {
        $needs = [];
        foreach ($users as $user) {
            foreach (self::$users as $item) {
                if ($user == $item['id']) {
                    $needs[] = $item;
                    break;
                }
            }
        }
        return $needs;
    }

    private static function getOrder($users, $list = [])
    {
        foreach ($users as $user) {
            if (!key_exists($user['id'], $list)) {
                // 订单总金额
                $total = self::_order(array_merge([$user['id']], $user['children']));
                $list[$user['id']] = $user;
                $list[$user['id']]['total'] = $total;
                // 佣金与比例
                $x = self::_amount($total);
                $list[$user['id']]['amount'] = $x[0];
                $list[$user['id']]['ratio'] = $x[1];
            }

            // 操作子团队业绩
            if (!empty($user['manager'])) {
                $manager = self::getData($user['manager']);
                $list = self::getOrder($manager, $list);
            }
        }

        return $list;
    }

    // 订单
    private static function _order($ids)
    {
        $orders = Order::find()
            // ->where(['is_repeat' => 1])
            ->andWhere(['user_id' => $ids])
            // 上个月的
            ->andWhere("date_format(create_time,'%Y-%m')=date_format(date_sub(curdate(), interval 1 month),'%Y-%m')")
            // 云仓提货不算
            ->andWhere(['is_extract' => 0])
            ->andWhere(['!=', 'status', Order::$statusMapping['NON_PAYMENT']])
            ->andWhere(['!=', 'status', Order::$statusMapping['CANCEL']])
            ->andWhere(['!=', 'status', Order::$statusMapping['DELETE']])
            ->andWhere(['!=', 'status', Order::$statusMapping['REFUND']])
            ->select(['id', 'total_pay', 'total_freight'])
            ->asArray()
            ->all();

        $sum = 0;
        foreach ($orders as $order) {
            $sum += $order['total_pay'] - $order['total_freight'];
        }

        return $sum;
    }

    // 佣金
    private static function _amount($total)
    {
        // $set = SetUserUp::getLastOne();
        //
        // $ratio = 0;
        // if ($total >= $set->new_repeat_start3) {
        //     $ratio = $set->new_repeat_ratio3;
        // } else if ($total >= $set->new_repeat_start2) {
        //     $ratio = $set->new_repeat_ratio2;
        // } else if ($total >= $set->new_repeat_start1) {
        //     $ratio = $set->new_repeat_ratio1;
        // }
        //
        // return [$ratio * $total / 100, $ratio];

        $total = (int)$total;

        // var_dump($total);

        $model = ZSetting::find()
            ->where(['<=', 'start', $total])
            ->andWhere(['>=', 'end', $total])
            ->one();

        if ($model) {
            $ratio = $model->amount / 100;
            return [$total * $ratio, $ratio];
        }

        return [0, 0];
    }
}